package com.zhongyewx.teachercert.base;

import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.classic.common.MultipleStatusView;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.zhongyewx.teachercert.R;
import com.zhongyewx.teachercert.ZYApplication;
import com.zhongyewx.teachercert.api.ZYARouterApi;
import com.zhongyewx.teachercert.utils.StatusBarUtil;
import com.zhongyewx.teachercert.utils.ZYClickUtil;
import com.zhongyewx.teachercert.utils.ZYToastUtil;
import com.zhongyewx.teachercert.views.ZYPtrClassicListHeader;

import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class ZYBaseActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{

    protected Toolbar toolbar;
    protected Context mContext;
    private TextView tvTitle;
    private TextView tvTitleRight;
    private ImageView imgTitleRight;
    private MultipleStatusView  mLayoutStatusView = null;
    protected PtrFrameLayout ptrFrameLayout = null;

    private Handler mHandler = new Handler();
    Runnable postDelayed = new Runnable() {
        @Override
        public void run() {
            ZYToastUtil.showCenterToast(ZYBaseActivity.this, "刷新失败请重试");
            if (ptrFrameLayout != null && ptrFrameLayout.isRefreshing()) {
                ptrFrameLayout.refreshComplete();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ZYApplication.getInstance().addActivity(this);
        PushAgent.getInstance(this).onAppStart();//统计
        setContentView(getLayoutId());
        process(savedInstanceState);
        setStatusBar();
        ARouter.getInstance().inject(this);
        mContext = this;
        initView();
        if (ptrFrameLayout != null){
            initPtr();
        }
        initData();
        request();
        initListener();
    }

    @Override
    public Lifecycle getLifecycle() {
        return super.getLifecycle();
    }

    /**
     *  加载布局
     */
    public abstract @LayoutRes int getLayoutId();

    /**
     * 初始化 View
     */
    public abstract void initView();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 请求数据
     */
    public abstract void request();

    public void PermissionsGranted(int requestCode){};

    private void initListener(){
        if (mLayoutStatusView != null)
            mLayoutStatusView.setOnRetryClickListener(mRetryClickListener);
    }
    /**
     * 初始化(配置)下拉刷新组件
     */
    private void initPtr() {
        float scale = getResources().getDisplayMetrics().density;
        ZYPtrClassicListHeader header = new ZYPtrClassicListHeader(this);
        header.setLastUpdateTimeRelateObject(this);
        header.setPadding(0, (int) (15 * scale + 0.5f), 0, (int) (15 * scale + 0.5f));
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                request();
                if (mHandler != null && postDelayed != null)
                    mHandler.postDelayed(postDelayed, 5000);
            }
        });
    }
    private Toolbar getToolbar() {
        if (toolbar == null) {
            toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setTitle("");
            setSupportActionBar(toolbar);
        }
        return toolbar;
    }
    /**
     * 添加toolbar标题
     */
    public void setToolbarTitle(String textTitle) {
        getToolbar().setTitle("");
        if (toolbar != null) {
            if (tvTitle == null) {
                tvTitle = (TextView) findViewById(R.id.app_title_text);
            }
            tvTitle.setText(textTitle);

        }
    }
    /**
     * 添加toolbar返回按键
     */
    public void setToolbarNavigationIcon(int resId) {
        getToolbar().setNavigationIcon(resId);

        setSupportActionBar(getToolbar());
        getToolbar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ZYClickUtil.isNotFastClick())
                    onClickLeftMenu();
            }
        });
    }
    /**
     * 去除 ToolbarNavigationIcon
     */
    public void setToolbarNavigationIcon() {
        if (getToolbar() != null) {
            getToolbar().setNavigationIcon(null);
        }
    }

    public void setToolbarTitleRightImg(int resId) {
        if (toolbar != null) {
            if (imgTitleRight == null) {
                imgTitleRight = (ImageView) findViewById(R.id.app_title_img_right);
            }
            imgTitleRight.setVisibility(View.VISIBLE);
            imgTitleRight.setImageResource(resId);
            imgTitleRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ZYClickUtil.isNotFastClick())
                        onClickRightMenu();
                }
            });
        }
    }

    public void setToolbarTitleRight(String txtRight, int txtColor) {
        if (toolbar != null) {
            if (tvTitleRight == null) {
                tvTitleRight = (TextView) findViewById(R.id.app_title_text_right);
            }
            tvTitleRight.setVisibility(View.VISIBLE);
            tvTitleRight.setText(txtRight);
            tvTitleRight.setTextColor(txtColor);
            tvTitleRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ZYClickUtil.isNotFastClick())
                        onClickRightMenu();
                }
            });
        }

    }
    /**
     * toolbar左边按钮点击事件
     */
    public void onClickLeftMenu() {
        super.onBackPressed();
    }

    /**
     * toolbar右边按钮点击事件
     */
    public void onClickRightMenu() {

    }
    View.OnClickListener mRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            request();
        }
    };


    protected void aRouterTurnLogin(String path){

        ARouter.getInstance().build(path).navigation(this, new NavCallback() {
            @Override
            public void onArrival(Postcard postcard) {
                finish();
            }

            @Override
            public void onInterrupt(final Postcard postcard) {
                ARouter.getInstance()
                        .build(ZYARouterApi.AROUTER_LOGIN_ACTY)
                        //拦截跳转的时候，后续登录成功后，继续跳转，需要这个url
                        .greenChannel()
//                            .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation(ZYBaseActivity.this);
                finish();
            }
        });
    }

    protected void ARouterTurnCustom(String path, final String interruptPath){

        ARouter.getInstance().build(path).navigation(this, new NavCallback() {
            @Override
            public void onArrival(Postcard postcard) {
                finish();
            }

            @Override
            public void onInterrupt(final Postcard postcard) {
                ARouter.getInstance()
                        .build(interruptPath)
                        //拦截跳转的时候，后续登录成功后，继续跳转，需要这个url
                        .greenChannel()
//                            .withFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .navigation(ZYBaseActivity.this);
                finish();
            }
        });
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (ptrFrameLayout != null && ptrFrameLayout.isRefreshing()) {
            ptrFrameLayout.refreshComplete();
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(postDelayed);
            mHandler = null;
            postDelayed = null;
        }
    }

    @Override
    protected void onDestroy() {
        ZYApplication.getInstance().removeActivity(this);
        super.onDestroy();
//        ZYApplication.getRefWatcher().watch(this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        PermissionsGranted(requestCode);
        Log.i("EasyPermissions", "获取成功的权限$perms");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        StringBuffer sb = new StringBuffer();
        for (String str : perms) {
            sb.append(str);
            sb.append("\n");
        }
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setRationale("此功能需要" + sb + "权限，否则无法正常使用，是否打开设置")
                    .setPositiveButton("好")
                    .setNegativeButton("不行")
                    .build()
                    .show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//qq  微博分享需要加的
    }

    protected void process(Bundle savedInstanceState) {
        // 华为,OPPO机型在StatusBarUtil.setLightStatusBar后布局被顶到状态栏上去了
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View content = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
            if (content != null && !isUseFullScreenMode()) {
                content.setFitsSystemWindows(true);
            }
        }
    }

    // 在setContentView之前执行
    public void setStatusBar() {
    /*
     为统一标题栏与状态栏的颜色，我们需要更改状态栏的颜色，而状态栏文字颜色是在android 6.0之后才可以进行更改
     所以统一在6.0之后进行文字状态栏的更改
    */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

//            if (getToolbar() != null) {
//                View view = findViewById(R.id.title_v);
//                ViewGroup.LayoutParams params = view.getLayoutParams();
//                params.height = getStatusBarHeight(this);
//                view.setLayoutParams(params);
//            }
            if (isUseFullScreenMode()) {
                StatusBarUtil.transparencyBar(this);
            } else {
                StatusBarUtil.setStatusBarColor(this, setStatusBarColor());
            }

            if (isUserLightMode()) {
                StatusBarUtil.setLightStatusBar(this, true);
            }
        } else {
            StatusBarUtil.setStatusBarColor(this, R.color.color_008577);
        }

    }
    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        // 获得状态栏高度
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    // 是否设置成透明状态栏，即就是全屏模式
    protected boolean isUseFullScreenMode() {
        return false;
    }

    protected int setStatusBarColor() {
        return R.color.white;
    }

    // 是否改变状态栏文字颜色为黑色，默认为黑色
    protected boolean isUserLightMode() {
        return true;
    }

}
